package fr.utbm.gi.in56.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.utbm.gi.in56.database.DatabaseServlet;
import fr.utbm.gi.in56.error.ErrorType;
import fr.utbm.gi.in56.notification.NotificationType;

/**
 * Servlet implementation class LoginServlet
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends DatabaseServlet
{
	/**
	 * Version number associated to the serializable class.
	 */
	private static final long	serialVersionUID	= -494883143030882648L;

	/**
	 * Default constructor.
	 * 
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet()
	{
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{	
		request.setCharacterEncoding( "UTF-8" ); //$NON-NLS-1$
		UserManager userMg = null;

		userMg = new UserManager( getConnection() );
		
		UserBean user		= new UserBean();
		user.setLogin(  request.getParameter( "login" ) ); //$NON-NLS-1$
		
		ErrorType result = null;
		
		try
		{
			result = userMg.connectUser( user, request.getParameter( "password" ) ); //$NON-NLS-1$
		}
		catch ( SQLException _exception )
		{
			_exception.printStackTrace();
			
			returnError( request, response, ErrorType.DB_ERROR );
			return;
		}		
		
		if ( result == ErrorType.NONE )
		{
			HttpSession session = request.getSession( true );
			session.setAttribute( "currentSessionUser", user ); //$NON-NLS-1$
			
			request.setAttribute( "notification", NotificationType.LOGIN_SUCCESS ); //$NON-NLS-1$
			RequestDispatcher rd = request.getRequestDispatcher("notification.jsp"); //$NON-NLS-1$
			rd.forward( request, response );
			return;
		}
		else
		{			
			returnError( request, response, result );
			return;
		}
	}
	
	/**
	 * Sets the error as request attribute and forward to previous page.
	 * 
	 * @param _error the error
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void returnError( HttpServletRequest request,
			HttpServletResponse response, ErrorType _error ) throws ServletException, IOException
	{
		request.setAttribute( "connectionError", _error ); //$NON-NLS-1$
		RequestDispatcher rd = request.getRequestDispatcher("connection.jsp"); //$NON-NLS-1$
		rd.forward( request, response );
	}
}
